//
//  JKPersonalInfoViewController.m
//  JKRecover
//
//  Created by Veer on 2018/6/3.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRRegisterViewController.h"

#import "JKPersonInfoCell.h"
#import "JKSelectorView.h"
#import "JKPersonInfoConfigModel.h"

#import "UIImage+VR.h"
#import <AddressBookUI/AddressBookUI.h>
#import <CoreLocation/CoreLocation.h>

#import "VRAreaListModel.h"


@interface VRRegisterViewController () <UITableViewDelegate, UITableViewDataSource, ABPeoplePickerNavigationControllerDelegate, UIAlertViewDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) JKSelectorView *selectorView;
@property (nonatomic, strong) UIButton *getVerCodeBtn;


@property (nonatomic, strong) NSMutableArray<NSMutableArray<JKPersonInfoConfigModel *> *> *sectionArray;

@property (nonatomic, weak) UITextField *curSelectedTextFeild;
@property (nonatomic, strong) NSIndexPath *curSelectedIndexPath;

@property (nonatomic, weak) UITextField *captchaTextFeild;


@property (nonatomic, copy) NSString *province;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *area;

// 关于定位
@property (nonatomic, strong) CLLocationManager *clMgr;
@property (nonatomic, strong) CLGeocoder *geo;
@property (nonatomic, strong) CLPlacemark *placemark;

@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, assign) BOOL isCountDown;

@property (nonatomic, strong) NSArray<VRAreaListModel *> *areaLiseModelArray;
@property (nonatomic, strong) NSArray<VRAreaListModel *> *placeLiseModelArray;
@property (nonatomic, assign) NSInteger curAreaSelectedIndex;
@property (nonatomic, assign) NSInteger curPlaceSelectedIndex;

@end

@implementation VRRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"注册账号";
    self.view.backgroundColor = ScrollViewBgColor;
    
    self.curAreaSelectedIndex = -1;
    self.curPlaceSelectedIndex = -1;
    
    [self setupSubView];
    [self setupBlock];
    
//    [self.clMgr startUpdatingLocation];
}

- (void)setupSubView
{
    [self.view addSubview:self.tableView];
    
    // 按钮
//    UIButton *finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [finishBtn setAdjustsImageWhenHighlighted:NO];
//    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
//    finishBtn.titleLabel.font = VRFont(16);
//    [finishBtn setTitleColor:RGB(0, 0, 0) forState:UIControlStateNormal];
//    [finishBtn setTitleColor:RGB(160, 160, 160) forState:UIControlStateHighlighted];
//    [finishBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateDisabled];
//    [finishBtn setBackgroundImage:[UIImage imageWithColor: RGB(254, 216, 48)] forState:UIControlStateNormal];
//    [finishBtn setBackgroundImage:[UIImage imageWithColor: RGB(206, 206, 206)] forState:UIControlStateDisabled];
//    [finishBtn addTarget:self action:@selector(onFinishBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    finishBtn.titleEdgeInsets = UIEdgeInsetsMake(-HOME_INDICATOR_HEIGHT*0.5, 0, HOME_INDICATOR_HEIGHT*0.5, 0);
//    [self.view addSubview:finishBtn];
//    [finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.mas_equalTo(0);
//        make.bottom.mas_equalTo(0);
//        make.left.mas_equalTo(0);
//        make.height.mas_equalTo(50 + HOME_INDICATOR_HEIGHT);
//    }];
    
    UIView *footerView = [[UIView alloc] init];
    footerView.frame = CGRectMake(0, 0, kScreenWidth, 200);
    self.tableView.tableFooterView = footerView;
    
    // 按钮
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.layer.cornerRadius = 6;
    [leftBtn setTitle:@"已有账号？" forState:UIControlStateNormal];
    leftBtn.titleLabel.font = VRFont(15);
    [leftBtn setTitleColor:MAINColor forState:UIControlStateNormal];
    [leftBtn setTitleColor:RGB(200, 200, 200) forState:UIControlStateHighlighted];
    [leftBtn addTarget:self action:@selector(goLogin) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [footerView addSubview:leftBtn];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(10);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(28);
    }];
    
    // 按钮
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.backgroundColor = RGB(78, 173, 57);
    loginBtn.layer.cornerRadius = 4;
    [loginBtn setTitle:@"注册" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = VRFont(16);
    [loginBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [loginBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [loginBtn addTarget:self action:@selector(onRegisterBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(leftBtn.mas_bottom).offset(10);
        make.width.mas_equalTo(kScreenWidth - 80);
        make.height.mas_equalTo(46);
    }];
    
    
}

- (void)setupBlock
{
    weakify(self)
    self.selectorView.sureBlock = ^(NSString *value, NSInteger index) {
        
        strongify(self)
        if (self.curSelectedIndexPath.row == 0) {
            self.curAreaSelectedIndex = index;
            self.placeLiseModelArray = nil;
            [self getPlaceListWihtIsShowDefault:YES];
        }else{
            self.curPlaceSelectedIndex = index;
        }
        
        NSMutableArray *modelArray = self.sectionArray[self.curSelectedIndexPath.section];
        JKPersonInfoConfigModel *model = modelArray[self.curSelectedIndexPath.row];
        model.value = value;
        
        self.curSelectedTextFeild.text = value;
    };
}


/** 住房情况 */
- (void)hoseArray
{
    NSArray *hoseArray = @[@"自购房未抵押", @"自购房已抵押", @"与父母同住但名下无房", @"租房", @"单位宿舍", @"其他"];
    self.selectorView.title = @"住房情况";
    self.selectorView.titleArray = hoseArray;
    [self.selectorView show];
}

/** 教育情况 */
- (void)culturalListArray
{
    NSArray *culturalListArray = @[@"小学", @"初中", @"高中", @"大专", @"本科", @"硕士", @"博士"];
    self.selectorView.title = @"文化情况";
    self.selectorView.titleArray = culturalListArray;
    [self.selectorView show];
}




/** 选择联系人 */
- (void)showContactSelector
{
    weakify(self)
    [self requestContactPermissionWith:^{
        
        strongify(self)
        ABPeoplePickerNavigationController *picker =[[ABPeoplePickerNavigationController alloc] init];
        picker.peoplePickerDelegate = self;
        
        NSString *version= [UIDevice currentDevice].systemVersion;
        
        if(version.doubleValue >= 8.0) {
            
            picker.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
        }
        [self presentViewController:picker animated:YES completion:nil];
    }];
    
}


- (void)requestContactPermissionWith:(void(^)(void))success
{
    // 判断是否授权
    ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus();
    if (authorizationStatus == kABAuthorizationStatusNotDetermined) {
        // 请求授权
        weakify(self)
        ABAddressBookRef addressBookRef = ABAddressBookCreate();
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
            
            strongify(self)
            if (granted) { // 授权成功
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                    [self showContactSelector];
                    if (success) {
                        success();
                    }
                });
            } else {  // 授权失败
                
                NSLog(@"授权失败！");
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"通讯录权限未开启，请进入系统［设置］> [隐私] > [通讯录]中开启" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil];
                    [alertView show];
                });
            }
        });
    }else if (authorizationStatus == kABAuthorizationStatusDenied || authorizationStatus == kABAuthorizationStatusRestricted){
        
        NSLog(@"关闭授权！");
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"通讯录权限未开启，请进入系统［设置］> [隐私] > [通讯录]中开启" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil];
        [alertView show];
    }else{
        
        if (success) {
            success();
        }
    }
}


- (void)startCountDown
{
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    weakify(self)
    dispatch_source_set_event_handler(_timer, ^{
        
        strongify(self)
        if(time <= 0){ //倒计时结束，关闭
            
            self.isCountDown = NO;
            dispatch_source_cancel(self.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                self.getVerCodeBtn.enabled = YES;
                [self.getVerCodeBtn setTitle:@"重新获取" forState:(UIControlStateNormal)];
                [self.getVerCodeBtn setTitleColor:RGB(254, 215, 49) forState:UIControlStateNormal];
                [self.getVerCodeBtn setTitle:@"获取验证码" forState:(UIControlStateDisabled)];
            });
            
        }else{
            
            self.isCountDown = YES;
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.getVerCodeBtn.enabled = NO;
                //                self.isCountdown = YES;
                [self.getVerCodeBtn setTitle:[NSString stringWithFormat:@"%ds", seconds] forState:(UIControlStateDisabled)];
                
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}


- (void)stopCountDown
{
    self.isCountDown = NO;
    dispatch_source_cancel(_timer);
}


#pragma mark - networking
- (void)userRegister
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = self.sectionArray[0][0].value;
    param[@"name"] = self.sectionArray[0][1].value;
    
    param[@"areaID"] = self.areaLiseModelArray[self.curAreaSelectedIndex].fID;
    param[@"PlaceID"] = self.placeLiseModelArray[self.curPlaceSelectedIndex].fID;
    param[@"fHouseNumber"] = self.sectionArray[1][2].value;
    
    param[@"code"] = self.captchaTextFeild.text;
    param[@"pwd"] = self.sectionArray[2][0].value;
    param[@"pwd1"] = self.sectionArray[2][1].value;
    
    weakify(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:Register_url parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            [SVProgressHUD showSuccessWithStatus:@"恭喜你注册成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                if (self.returnBlock) {
                    self.returnBlock(self.sectionArray[0][0].value);
                }
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else if(msg.length > 0){
            [SVProgressHUD showErrorWithStatus:msg];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
    } error:^(NSError * _Nonnull error) {
        
    }];
}


- (void)getCapcha
{

    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    
    NSString *timeStampStr = [NSString stringWithFormat:@"%.0lf", timeStamp];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = self.sectionArray[0][0].value;
//    param[@"timestamp"] = timeStampStr;
    
    weakify(self)
    [JKNetworking postWithSign:GetCaptcha_url parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self startCountDown];
            });
        }else if(msg.length > 0){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.getVerCodeBtn.enabled = YES;
                [SVProgressHUD showErrorWithStatus:msg];
            });
        }
    } error:^(NSError * _Nonnull error) {
        
    }];
}

- (void)getAreaList
{
    

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    weakify(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:GetAreaList_url parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            self.areaLiseModelArray = [VRAreaListModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self showAreaList];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
        }else if(msg.length > 0){
            [SVProgressHUD showErrorWithStatus:msg];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
    } error:^(NSError * _Nonnull error) {
        
    }];
}


- (void)getPlaceListWihtIsShowDefault:(BOOL)isShowDefault
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"areaID"] = self.areaLiseModelArray[self.curAreaSelectedIndex].fID;
    
    weakify(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:GetPlaceList_url parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            
            self.placeLiseModelArray = [VRAreaListModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (isShowDefault) {
                    
                    self.curPlaceSelectedIndex = 0;
                    self.sectionArray[1][1].value = [self.placeLiseModelArray firstObject].fAreaName;
                    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
                }else{
                    [self showPlaceList];
                }
                
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
        }else if(msg.length > 0){
            [SVProgressHUD showErrorWithStatus:msg];
        }
    } error:^(NSError * _Nonnull error) {
        
    }];
}


#pragma mark - action
- (void)onRegisterBtnClick:(UIButton *)sender
{
    for (NSMutableArray *sectionArray in self.sectionArray) {
        
        for (JKPersonInfoConfigModel *model in sectionArray) {
            
            if (model.value.length == 0) {
                
                NSString *name = model.name.length == 0 ? @"详细地址" : model.name;
                name = [name stringByReplacingOccurrencesOfString:@"：" withString:@""];
                NSString *msg = [NSString stringWithFormat:@"%@不能为空", name];
                [SVProgressHUD showErrorWithStatus:msg];
                return;
            }
        }
    }
    if (self.captchaTextFeild.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"验证码不能为空"];
        return;
    }
    
    [self userRegister];
    
//    if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
//    {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"定位服务未开启，请进入系统［设置］> [隐私] > [位置]中打开开关" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil];
//        [alertView show];
//        return;
//    }
    
//    weakify(self)
//    [self requestContactPermissionWith:^{
//        strongify(self)
//
//    }];
}

- (void)onGetVerCodeBtnClick:(UIButton *)sender
{
//    [self startCountDown];
    
    if (self.sectionArray[0][0].value.length == 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        });
        return;
    }
    
    if ([NSString valiMobile:self.sectionArray[0][0].value]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        });
        return;
    }else{
        sender.enabled = NO;
    }
    [self getCapcha];
}

- (void)goLogin
{
    [self.navigationController popViewControllerAnimated:YES];
}

/** 居住时长 */
- (void)showAreaList
{

    self.selectorView.title = @"所在区域";
    if (self.areaLiseModelArray.count > 0) {
        
        NSMutableArray *titleArray = [NSMutableArray array];
        [self.areaLiseModelArray enumerateObjectsUsingBlock:^(VRAreaListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [titleArray addObject:obj.fPrefecture];
        }];
        self.selectorView.titleArray = [titleArray copy];
        [self.selectorView show];
    }else{
        [self getAreaList];
    }
}


/** 关系 */
- (void)showPlaceList
{
    
    self.selectorView.title = @"所在小区";
    if (self.placeLiseModelArray.count > 0) {
        
        NSMutableArray *titleArray = [NSMutableArray array];
        [self.placeLiseModelArray enumerateObjectsUsingBlock:^(VRAreaListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [titleArray addObject:obj.fAreaName];
        }];
        self.selectorView.titleArray = [titleArray copy];
        [self.selectorView show];
    }else{
        [self getPlaceListWihtIsShowDefault:NO];
    }
}

#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return 44;
    }
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section != 2) {
        return nil;
    }
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    headerView.backgroundColor = [UIColor whiteColor];
    
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"验证码：";
    titleLbl.textColor = RGB(50, 50, 50);
    titleLbl.font = VRFont(16);
    titleLbl.frame = CGRectMake(15, 0, 70, 44);
    [headerView addSubview:titleLbl];
    
    UITextField *tf = [[UITextField alloc] init];
    tf.tag = 1001;
    tf.font = VRFont(16);
    tf.textColor = [UIColor blackColor];
    [tf setValue:RGB(107, 198, 255) forKeyPath:@"_placeholderLabel.textColor"];
    tf.placeholder = @"请输入验证码";
    tf.frame = CGRectMake(120, 0, kScreenWidth - CGRectGetMaxX(titleLbl.frame) - 70 - 15, 44);
//    tf.delegate = self;
//    [tf addTarget:self action:@selector(textFieldTextChanged:) forControlEvents:UIControlEventEditingChanged];
    [headerView addSubview:tf];
    self.captchaTextFeild = tf;
    
    
    UIButton *getVerCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    getVerCodeBtn.tag = 1003;
    getVerCodeBtn.layer.cornerRadius = 4;
    getVerCodeBtn.layer.masksToBounds = YES;
    [getVerCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [getVerCodeBtn setTitleColor:MAINColor forState:UIControlStateNormal];
    [getVerCodeBtn setTitleColor:RGB(150, 150, 150) forState:UIControlStateDisabled];
    [getVerCodeBtn setBackgroundImage:[UIImage imageWithColor:RGB(101, 183, 224)] forState:UIControlStateNormal];
    [getVerCodeBtn setBackgroundImage:[UIImage imageWithColor:RGB(220, 220, 220)] forState:UIControlStateDisabled];
    getVerCodeBtn.titleLabel.font =  VRFont(12);
    //            getVerCodeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [getVerCodeBtn addTarget:self action:@selector(onGetVerCodeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:getVerCodeBtn];
    getVerCodeBtn.frame = CGRectMake(kScreenWidth - 70 - 15, 0, 70, 30);
    getVerCodeBtn.centerY = 22;
    self.getVerCodeBtn = getVerCodeBtn;
    
    UIView *bottomLineView = [[UIView alloc] init];
    bottomLineView.backgroundColor = RGB(228, 228, 228);
    bottomLineView.frame = CGRectMake(15, 44 - 0.5, kScreenWidth - 15, 0.5);
    [headerView addSubview:bottomLineView];
    
    return headerView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    return @" ";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSMutableArray *modelArray = self.sectionArray[section];
    return modelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *modelArray = self.sectionArray[indexPath.section];
    JKPersonInfoConfigModel *model = modelArray[indexPath.row];
    
    JKPersonInfoCell *cell = [JKPersonInfoCell cellWith:tableView];
    cell.model = model;
    
    weakify(self)
    cell.textFieldClickBlock = ^(UITextField *textField) {
        
        strongify(self)
        
        self.curSelectedTextFeild = textField;
        self.curSelectedIndexPath = indexPath;
        
        //        if (indexPath.section == 1 && indexPath.row == 0) {
        //
        //            [self.view endEditing:YES];
        //            [self.areaSelectorView show];
        //            return;
        //        }
        
        if (!model.isCanEdit) {
            [self.view endEditing:YES];
        }
        
        if (model.performName.length > 0) {
            
            [self.view endEditing:YES];
            if ([self respondsToSelector:NSSelectorFromString(model.performName)]) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self performSelector:NSSelectorFromString(model.performName) withObject:nil];
                });
            }
        }
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSMutableArray *modelArray = self.sectionArray[indexPath.section];
    JKPersonInfoConfigModel *model = modelArray[indexPath.row];
}

#pragma mark locationDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    CLLocation *loc = locations.lastObject;
    [VRUser shareUser].latitude = loc.coordinate.latitude;
    [VRUser shareUser].longitude = loc.coordinate.longitude;
    
    NSLog(@"locationManager:lat:%lf, lng:%lf", loc.coordinate.latitude, loc.coordinate.longitude);
    
    [self.clMgr stopUpdatingLocation];
}


- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"定位服务未开启，请进入系统［设置］> [隐私] > [位置]中打开开关" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil];
        [alertView show];
    }else if (status != kCLAuthorizationStatusNotDetermined){
        
        
    }
}


#pragma mark alertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        
        if([[UIApplication sharedApplication] canOpenURL:url]) {
            
            NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}


#pragma mark ABPeoplePickerNavigationControllerDelegate
//这个方法在用户取消选择时调用
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

//这个方法在用户选择一个联系人后调用
-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person{
    //    [self displayPerson:person];
    //    [self dismissViewControllerAnimated:YES completion:^{}];
    ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
    personViewController.displayedPerson = person;
    
    [peoplePicker pushViewController:personViewController animated:YES];
}


- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    [self displayPerson:person];
    [self dismissViewControllerAnimated:YES completion:^{}];
}


//获得选中person的信息
- (void)displayPerson:(ABRecordRef)person
{
    NSString *firstName = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString *middleName = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
    NSString *lastname = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);
    NSMutableString *nameStr = [NSMutableString string];
    if (lastname!=nil) {
        [nameStr appendString:lastname];
    }
    if (middleName!=nil) {
        [nameStr appendString:middleName];
    }
    if (firstName!=nil) {
        [nameStr appendString:firstName];
    }
    
    NSString* phone = nil;
    ABMultiValueRef phoneNumbers = ABRecordCopyValue(person,kABPersonPhoneProperty);
    if (ABMultiValueGetCount(phoneNumbers) > 0) {
        phone = (__bridge_transfer NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, 0);
    } else {
        phone = @"[None]";
    }
    
    //可以把-、+86、空格这些过滤掉
    NSString *phoneStr = [phone stringByReplacingOccurrencesOfString:@"-" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"+86" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"(" withString:@""];
    phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@")" withString:@""];
    phoneStr = [[phoneStr componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
    
    NSMutableArray *modelArray = self.sectionArray[self.curSelectedIndexPath.section];
    JKPersonInfoConfigModel *model = modelArray[self.curSelectedIndexPath.row];
    model.value = phoneStr;
    
    self.curSelectedTextFeild.text = phoneStr;
}

#pragma mark - lazy
- (UITableView *)tableView
{
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.01)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 0;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        [self.view addSubview:self.tableView];
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.view);
            make.top.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
        }];
        
        
        UIView *headerView = [[UIView alloc] init];
        headerView.frame = CGRectMake(0, 0, kScreenWidth, 20);
        
//        UIImageView *topImgView = [[UIImageView alloc] init];
//        topImgView.contentMode = UIViewContentModeScaleAspectFit;
//        topImgView.image = [UIImage imageNamed:@"icon_base_info"];
//        topImgView.frame = CGRectMake(0, 16, kScreenWidth, 112 - 16);
//        [headerView addSubview:topImgView];
        
        _tableView.tableHeaderView = headerView;
    }
    return _tableView;
}

- (JKSelectorView *)selectorView
{
    if (_selectorView == nil) {
        
        _selectorView = [[JKSelectorView alloc] init];
    }
    return _selectorView;
}


- (NSMutableArray<NSMutableArray<JKPersonInfoConfigModel *> *> *)sectionArray
{
    if (_sectionArray == nil) {
        
        NSString *path =  [[NSBundle mainBundle] pathForResource:@"VRRegister" ofType:@"plist"];
        _sectionArray = [NSMutableArray arrayWithArray:[JKPersonInfoConfigModel mj_objectArrayWithFile:path]];
        
        NSLog(@"");
    }
    return _sectionArray;
}


- (CLLocationManager *)clMgr
{
    if (nil == _clMgr) {
        _clMgr = [[CLLocationManager alloc] init];
        _clMgr.delegate = self;
        _clMgr.desiredAccuracy = kCLLocationAccuracyBest;
        //        _clMgr.allowsBackgroundLocationUpdates = YES;
        if ([_clMgr respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            NSLog(@"requestAlwaysAuthorization");
            [_clMgr requestAlwaysAuthorization];
        }
        
        //开始定位，不断调用其代理方法
        [_clMgr requestWhenInUseAuthorization];
    }
    return _clMgr;
}


#pragma mark - tool
-(NSString *)convertToJsonData:(id)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0, jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}


///** 住房情况 */
//- (NSMutableArray *)hoseInfo
//{
//    NSArray *house = @[@"自购房未抵押", @"自购房已抵押", @"与父母同住但名下无房", @"租房", @"单位宿舍", @"其他"];
//
//    NSArray *culturalListArray = @[@"小学", @"初中", @"高中", @"大专", @"本科", @"硕士", @"博士"];
//
//    NSArray *liveLenthArray = @[@"1-3个月", @"3-6个月", @"6-12个月", @"12-24个月", @"24个月"];
//
//    NSArray *relationshipArray = @[@"父亲", @"母亲", @"配偶", @"子女"];
//
//    return nil;
//}

@end
